﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using DocumentBuilder.Controls.Utils;

namespace DocumentBuilder.Controls
{
    public class HtmlControl : IControl
    {
        private const string HtmlNodeFormat = "<{0} {1}>{2}</{0}>";
        private const string AttributeFormat = "{0}=\"{1}\"";
        private String CoverHtml { get; set; }

        public List<IControl> Children { get; private set; }

        private HtmlControl()
        {
            Children = new List<IControl>();
        }

        public static HtmlControl Create(Document context, XmlNode controlNode)
        {
            var htmlControl = new HtmlControl();

            if (controlNode == null)
            {
                htmlControl.CoverHtml = String.Empty;
            }
            else
            {
                var attrPaintString = new StringBuilder();

                if (controlNode.Attributes != null)
                {
                    foreach (XmlNode attributeNode in controlNode.Attributes)
                    {
                        attrPaintString.Append(String.Format(AttributeFormat, attributeNode.Name, attributeNode.Value));
                    }
                }

                htmlControl.CoverHtml = String.Format(HtmlNodeFormat, controlNode.Name, attrPaintString.ToString(), "{0}");
            }

            /* Parse and add child controls in the collection
             */
            ControlBuilder.ParseChildControls(context, controlNode, htmlControl.Children);

            return htmlControl;
        }

        #region IControl Members

        public void PaintHtmlString(StringBuilder htmlCanvas)
        {
            var paintString = new StringBuilder();
            foreach (IControl control in Children)
            {
                control.PaintHtmlString(paintString);
            }

            htmlCanvas.AppendLine(String.Format(CoverHtml, paintString.ToString()));
        }

        #endregion
    }
}
